package com.web.controller.system;

import com.domain.system.Dept;
import com.domain.system.Module;
import com.domain.system.Role;
import com.domain.system.User;
import com.github.pagehelper.PageInfo;
import com.service.system.impl.DeptServiceImpl;
import com.utils.BeanUtil;
import com.web.controller.BaseServlet;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;

@WebServlet("/system/user")
public class UserServlet extends BaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String opera = request.getParameter("operation");
        if ("list".equals(opera)){
            list(request,response);
        }else if ("save".equals(opera)){
            save(request,response);
        }else if ("toAdd".equals(opera)){
            toAdd(request,response);
        }else if ("delete".equals(opera)){
            delete(request,response);
        }else if ("edit".equals(opera)){
            edit(request,response);
        }else if ("toEdit".equals(opera)){
            toEdit(request,response);
        }else if ("userRoleList".equals(opera)){
            //获取用户角色信息
            userRoleList(request,response);
        }else if ("updateRole".equals(opera)){
            //添加修改权限
            updateRole(request,response);
        }else if ("login".equals(opera)){
            //登录功能
            login(request,response);
        }else if ("main".equals(opera)){
            main(request,response);
        }else if ("logout".equals(opera)){
            //注销
            logout(request,response);
        }
    }

    private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //注销
        request.removeAttribute("user");
        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }

    private void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //转发
        request.getRequestDispatcher("/WEB-INF/pages/home/home.jsp").forward(request,response);
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //获取用户输入的信息
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        //调用业务层,查询数据
        User user = userService.findByLogin(email,password);
        if (user != null){
            //存入域中
            request.setAttribute("loginUser",user);
            //登录成功,加载用户所拥有的模块
            List<Module> modules = userService.findModuleByUserId(user.getId());
            //存入域中
            request.setAttribute("moduleList",modules);
            //将modules里面的curl拼接成字符串存入session
            StringBuffer str = new StringBuffer();
            for (Module module : modules) {
                str.append(module.getCurl());
                str.append(",");
            }
            request.getSession().setAttribute("authorStr",str.toString());
            //转发
            request.getRequestDispatcher("/WEB-INF/pages/home/main.jsp").forward(request,response);
        }else {
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }
    }

    private void updateRole(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //获取用户id
        String userId = request.getParameter("userId");
        System.out.println(userId);
        //获取角色id
        String[] roleIds = request.getParameterValues("roleIds");
        System.out.println(Arrays.toString(roleIds));
        //调用业务层,建立角色和用户之间的关联
        userService.updateRole(userId,roleIds);
        //跳转list页面
        //重定向
        response.sendRedirect(request.getContextPath()+"/system/user?operation=list");
    }

    private void userRoleList(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //获取参数Id
        String id = request.getParameter("id");
        //根据id获取当前用户
        User user = userService.findById(id);
        //将数据传入域中
        request.setAttribute("user",user);

        //查询所有角色信息
        List<Role> roles = roleService.findAllRoleByUserId(id);
        //存入域中
        request.setAttribute("roleList",roles);
        //转发
        request.getRequestDispatcher("/WEB-INF/pages/system/user/role.jsp").forward(request,response);
    }

    private void toEdit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //根据id查询
        String id = request.getParameter("id");
        User user = userService.findById(id);
        //存入域中
        request.setAttribute("user",user);
        List<Dept> all = deptService.findAll();
        request.setAttribute("deptList",all);
        //转发
        request.getRequestDispatcher("/WEB-INF/pages/system/user/update.jsp").forward(request,response);
    }

    private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //封装数据
        User user = BeanUtil.fillBean(request, User.class, "yyyy-MM-dd");
        //调用业务层代码
        userService.update(user);
        //重定向
        response.sendRedirect(request.getContextPath()+"/system/user?operation=list");
    }

    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //得到参数id
        User user = BeanUtil.fillBean(request, User.class);
        //调用业务层
        userService.delete(user);
        //重定向
        response.sendRedirect(request.getContextPath()+"/system/user?operation=list");
    }

    private void save(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //封装数据
        User user = BeanUtil.fillBean(request, User.class, "yyyy-MM-dd");
        //调用业务层代码
        userService.save(user);
        //重定向
        response.sendRedirect(request.getContextPath()+"/system/user?operation=list");
    }

    private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //得到所有的部门信息并放入到deptList
        List<Dept> all = deptService.findAll();
        request.setAttribute("deptList",all);
        //转发至添加页面
        request.getRequestDispatcher("/WEB-INF/pages/system/user/add.jsp").forward(request,response);
    }

    private void list(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //定义当前页和每页条数
        int page = 1;
        int size = 5;
        //得到参数page和size
        if (StringUtils.isNoneBlank(request.getParameter("page"))){
            page = Integer.parseInt(request.getParameter("page"));
        }
        if (StringUtils.isNoneBlank(request.getParameter("size"))){
            size = Integer.parseInt(request.getParameter("size"));
        }
        //调用业务层
        PageInfo all = userService.findAll(page, size);
        //存至域中
        request.setAttribute("page",all);
        //转发至list.jsp页面
        request.getRequestDispatcher("/WEB-INF/pages/system/user/list.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
